ReactJS Ultra For Beginners

🌳 Virtual DOM


What is Virtual DOM?

  • A lightweight copy of the actual DOM in memory
  • React's reconciliation algorithm compares Virtual DOM with real DOM
  • Only updates the parts of the DOM that actually changed
  • Improves performance by minimizing expensive DOM operations

📝 How Virtual DOM Works

1. Render Phase:

// React creates Virtual DOM representation function UserList({ users }) { return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } // Virtual DOM structure (simplified): { type: 'ul', props: { children: [ { type: 'li', props: { children: 'John Doe' }, key: 1 }, { type: 'li', props: { children: 'Jane Smith' }, key: 2 } ] } }

2. Reconciliation Process:

// When state changes, React: // 1. Creates new Virtual DOM // 2. Compares with previous Virtual DOM // 3. Calculates minimal changes needed // 4. Updates only the changed parts of real DOM function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } // When count changes from 0 to 1: // - Only the text content "Count: 0" → "Count: 1" is updated // - The div, h1, and button elements remain unchanged

🔑 Key Concepts

1. Diffing Algorithm:

// React compares elements by type and key function TodoList({ todos }) { return ( <ul> {todos.map((todo) => ( <li key={todo.id}> {" "} {/* Key helps React identify elements */} {todo.text} </li> ))} </ul> ); } // Without key, React might re-render all list items // With key, React can efficiently update only changed items

2. Element Types:

// Different element types cause full re-render function ConditionalRender({ showUser }) { return ( <div> {showUser ? ( <UserProfile /> // Component type ) : ( <div>Loading...</div> // DOM element type )} </div> ); } // When showUser changes, React will: // - Unmount UserProfile component // - Mount new div element // - This is expensive, so avoid changing element types frequently

3. Props Comparison:

function UserCard({ user, onEdit }) { return ( <div> <h2>{user.name}</h2> <p>{user.email}</p> <button onClick={onEdit}>Edit</button> </div> ); } // React compares props: // - If user object reference changes → re-render // - If onEdit function reference changes → re-render // - If props are the same → skip re-render

🎯 Performance Optimization

1. Key Prop Best Practices:

// ❌ Bad - using index as key function TodoList({ todos }) { return ( <ul> {todos.map((todo, index) => ( <li key={index}> {" "} {/* Index changes when items are reordered */} {todo.text} </li> ))} </ul> ); } // ✅ Good - using stable, unique keys function TodoList({ todos }) { return ( <ul> {todos.map((todo) => ( <li key={todo.id}> {" "} {/* Stable ID */} {todo.text} </li> ))} </ul> ); } // ✅ Alternative - using content hash function TodoList({ todos }) { return ( <ul> {todos.map((todo) => ( <li key={`${todo.id}-${todo.text}`}>{todo.text}</li> ))} </ul> ); }

2. Avoiding Unnecessary Re-renders:

// ❌ Bad - new object created on every render function ParentComponent() { const [count, setCount] = useState(0); const user = { name: "John", email: "john@example.com" }; // New object each render return ( <div> <p>Count: {count}</p> <UserCard user={user} /> {/* Will re-render every time */} <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } // ✅ Good - stable object reference function ParentComponent() { const [count, setCount] = useState(0); const user = useMemo( () => ({ name: "John", email: "john@example.com", }), [] ); // Stable reference return ( <div> <p>Count: {count}</p> <UserCard user={user} /> {/* Won't re-render unnecessarily */} <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }

3. Memoization:

// React.memo prevents unnecessary re-renders const UserCard = React.memo(({ user, onEdit }) => { console.log("UserCard rendered"); // Only logs when props actually change return ( <div> <h2>{user.name}</h2> <p>{user.email}</p> <button onClick={onEdit}>Edit</button> </div> ); }); // useMemo for expensive calculations function ExpensiveComponent({ items, filter }) { const filteredItems = useMemo(() => { console.log("Filtering items..."); // Only runs when dependencies change return items.filter((item) => item.name.includes(filter)); }, [items, filter]); return ( <ul> {filteredItems.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }

🔧 Advanced Patterns

1. Fragment Optimization:

// ❌ Bad - extra DOM node function UserInfo({ user }) { return ( <div> {" "} {/* Unnecessary wrapper */} <h1>{user.name}</h1> <p>{user.email}</p> </div> ); } // ✅ Good - no extra DOM node function UserInfo({ user }) { return ( <> <h1>{user.name}</h1> <p>{user.email}</p> </> ); } // ✅ Alternative - named fragment function UserInfo({ user }) { return ( <React.Fragment> <h1>{user.name}</h1> <p>{user.email}</p> </React.Fragment> ); }

2. Portal Usage:

import { createPortal } from "react-dom"; function Modal({ isOpen, children }) { if (!isOpen) return null; // Render outside normal DOM hierarchy return createPortal( <div className="modal">{children}</div>, document.body // Target DOM node ); } // Usage function App() { const [showModal, setShowModal] = useState(false); return ( <div> <button onClick={() => setShowModal(true)}>Open Modal</button> <Modal isOpen={showModal}> <h2>Modal Content</h2> <button onClick={() => setShowModal(false)}>Close</button> </Modal> </div> ); }

3. Error Boundaries:

class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error("Error caught by boundary:", error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } // Usage function App() { return ( <ErrorBoundary> <UserProfile /> </ErrorBoundary> ); }

⚠️ Common Pitfalls

1. Mutating State Directly:

// ❌ Bad - mutating state directly function TodoList() { const [todos, setTodos] = useState([]); const addTodo = (text) => { todos.push({ id: Date.now(), text }); // Mutating array setTodos(todos); // React won't detect the change }; return (/* JSX */); } // ✅ Good - creating new state function TodoList() { const [todos, setTodos] = useState([]); const addTodo = (text) => { setTodos(prevTodos => [...prevTodos, { id: Date.now(), text }]); }; return (/* JSX */); }

2. Inline Functions:

// ❌ Bad - new function on every render function UserList({ users }) { return ( <ul> {users.map((user) => ( <UserCard key={user.id} user={user} onEdit={() => editUser(user.id)} // New function each render /> ))} </ul> ); } // ✅ Good - memoized function function UserList({ users }) { const handleEdit = useCallback((userId) => { editUser(userId); }, []); return ( <ul> {users.map((user) => ( <UserCard key={user.id} user={user} onEdit={() => handleEdit(user.id)} /> ))} </ul> ); }

🎯 Best Practices

  1. Always use stable keys - avoid array indices for dynamic lists
  2. Avoid inline objects/functions - they cause unnecessary re-renders
  3. Use React.memo for expensive components - prevent unnecessary updates
  4. Optimize with useMemo and useCallback - memoize expensive calculations
  5. Keep components focused - smaller components are easier to optimize
  6. Use React DevTools - profile and identify performance bottlenecks
  7. Avoid premature optimization - measure first, optimize second